package com.xiaowen.config.security;

import com.xiaowen.tool.JsonUtils;
import com.xiaowen.tool.dto.Result;
import com.xiaowen.tool.jwt.JWTUtil;
import com.xiaowen.user.entity.User;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created with IntelliJ IDEA.
 * User: yf-wenhao
 * Date: 2024/9/18
 * Time: 下午4:55
 */
@Component
public class MyAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        Result<Object> objectResult = new Result<>();
        //jwt token
        if (authentication instanceof SmsCodeAuthenticationToken) {
            User user = (User) authentication.getPrincipal();
            String phoneNumber = user.getPhoneNumber();
            // 生成 jwt
            String jwt = JWTUtil.createJWT(phoneNumber);
            objectResult.ok(jwt);
        }
        response.setContentType("application/json;charset=UTF-8");
        String s = JsonUtils.toJson(objectResult);
        response.getWriter().println(s);
    }
}
